/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.shortlink.GenerateShortLinkRequest;
import cn.binarywang.wx.miniapp.bean.urllink.GenerateUrlLinkRequest;
import cn.binarywang.wx.miniapp.bean.urllink.request.QueryUrlLinkRequest;
import cn.binarywang.wx.miniapp.bean.urllink.response.QueryUrlLinkResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import dm.jdbc.util.StringUtil;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.controller.im.TencentCloudImUtil;
import io.renren.dto.*;
import io.renren.dto.queryDto.ParByKeyQuery;
import io.renren.dto.queryDto.StoreQuery;
import io.renren.dto.queryDto.VinQuery;
import io.renren.dto.repon.UcmlOrganizeRepon;
import io.renren.entity.*;
import io.renren.factory.FeginClientFactory;
import io.renren.service.*;
import io.renren.utils.WechatMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/index")
@Api(tags = "登录接口")
@AllArgsConstructor
public class ApiIndexController {

    @Autowired
    private AutobrandService autobrandService;
    @Autowired
    private AutogroupService autogroupService;
    @Autowired
    private AutokindsService autokindsService;
    @Autowired
    private AutomodelsService automodelsService;
    @Autowired
    private UcmlOrganizeService ucmlOrganizeService;
    @Autowired
    private SysparamService sysparamService;
    @Autowired
    private WxsendmbillService wxsendmbillService;

    //    @Value("${upload.path}")
    //    private String uploadPath;
    //
    //    @Value("${im.sdkappid}")
    //    private String sdkappid;
    //
    //    @Value("${im.adminUserId}")
    //    private String identifier;
    //    @PostMapping("/upload")
    //    public Result uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
    //        for (MultipartFile file : files) {
    //            try {
    //                file.transferTo(new File(Paths.get(uploadPath, file.getOriginalFilename()).toString()));
    //            } catch (IOException e) {
    //                e.printStackTrace();
    //                return new Result<>().error("File upload failed: " + e.getMessage());
    //            }
    //        }
    //        return new Result<>().ok("File(s) uploaded successfully");
    //    }

    @Autowired
    private ImgroupallbillService imgroupallbillService;
    @Autowired
    private AutorepairmService autorepairmService;
    @Autowired
    private AutodecoratemService autodecoratemService;
    @Autowired
    private TradermService tradermService;

    @PostMapping("sendWxMessage")
    @ApiOperation("推送消息")
    public Result sendWxMessage(@RequestBody SendInfoDto dto) {
        TradermEntity userInfo = tradermService.findOneByTel(dto.getUserId());
        if (userInfo != null && StringUtil.isNotEmpty(userInfo.getWxopenid())) {
            // 获取 IMGroupInfo
            ImgroupallbillEntity imgroupallbill = imgroupallbillService.findOneByImgroupid(dto.getGroupId());
            if (imgroupallbill != null) {
                String sourcebilltype = imgroupallbill.getSourcebilltype();
                String sourceBillOID = imgroupallbill.getSourcebilloid(); // 这个关联维修单表的AutoRepairMOID、美容单的AutoDecorateMOID
                /**
                 * 取维修、美容单上的项目名称ProjectName（多个项目用“分号”分隔）、门店名称orgName、金额repairAmount
                 * SourceBillType ： AAR   维修单 AutoRepairM
                 * SourceBillType ： AAD   美容单 AutoDecorateM
                 * SourceBillOID ： 这个关联维修单表的AutoRepairMOID、美容单的AutoDecorateMOID
                 */
                if ("AAR".equals(sourcebilltype)) {
                    // AutoRepairM
                    RepairDetailDto dtoAutoRepairM = new RepairDetailDto();
                    dtoAutoRepairM.setAutoRepairMoId(sourceBillOID);
                    Map<String, Object> autorepairm = autorepairmService.autoRepairDetail(null, dtoAutoRepairM);
                    if (autorepairm != null) {
                        if (dto.getCarNumber().isEmpty()) {
                            dto.setCarNumber(autorepairm.get("GiveRepairTraderName").toString());
                        }
                        String projectName = "";
                        String projectListStr = JSONObject.toJSONString(autorepairm.get("projectList"));
                        JSONArray jsonArray = JSONArray.parseArray(projectListStr);
                        StringBuilder resultBuilder = new StringBuilder();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            String itemProjectName = obj.getString("projectName");
                            if (i > 0) {
                                resultBuilder.append("; ");
                            }
                            resultBuilder.append(itemProjectName);
                        }

                        projectName = resultBuilder.toString();

                        dto.setThing2(projectName); // 实施项目
                        dto.setThing7(autorepairm.get("routineTestRemark").toString()); // 检测结果
                        dto.setAmount11(autorepairm.get("Amount").toString());
                        dto.setThing17(autorepairm.get("orgName").toString());
                        dto.setThing4(autorepairm.get("orgName").toString());
                        dto.setThing13(autorepairm.get("orgName").toString());
                        dto.setThing5(autorepairm.get("orgName").toString());
                    }

                } else if ("AAD".equals(sourcebilltype)) {
                    // AutoDecorateM
                    DecorateDetailDto dtoAutoDecorateM = new DecorateDetailDto();
                    dtoAutoDecorateM.setAutoDecorateMoId(sourceBillOID);
                    Map<String, Object> autodecoratem = autodecoratemService.autoDecorateDetail(null, dtoAutoDecorateM);
                    if (autodecoratem != null) {
                        if (dto.getCarNumber().isEmpty()) {
                            dto.setCarNumber(autodecoratem.get("GiveRepairTraderName").toString());
                        }
                        String projectName = "";
                        String projectListStr = JSONObject.toJSONString(autodecoratem.get("projectList"));
                        JSONArray jsonArray = JSONArray.parseArray(projectListStr);
                        StringBuilder resultBuilder = new StringBuilder();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            String itemProjectName = obj.getString("projectName");
                            if (i > 0) {
                                resultBuilder.append("; ");
                            }
                            resultBuilder.append(itemProjectName);
                        }

                        projectName = resultBuilder.toString();
                        dto.setThing2(projectName); // 实施项目

                        dto.setAmount11(autodecoratem.get("Amount").toString());
                        dto.setThing17(autodecoratem.get("orgName").toString());
                        dto.setThing4(autodecoratem.get("orgName").toString());
                        dto.setThing13(autodecoratem.get("orgName").toString());
                        dto.setThing5(autodecoratem.get("orgName").toString());
                    }
                }
                WechatMsg.sendMsg(dto, userInfo.getWxopenid());
                wxsendmbillService.addInfo(dto.getUserId(), dto.getGroupId(), dto.getType());
            }
        }
        return new Result();
    }

    @PostMapping("getSendWxMessageStatus")
    @ApiOperation("获取可以推送消息状态")
    public Result getSendWxMessageStatus(@RequestBody SendInfoDto dto) {
        Long count = wxsendmbillService.getLasterSendStatus(dto.getUserId(), dto.getType(), dto.getGroupId());
        if (count > 0) {
            ParByKeyQuery query = new ParByKeyQuery();
            query.setKey("GroupMsgCount");
            ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getQuerySysParByKey(query);
            if (result != null) {
                String dataStr = result.getData().toString();
                if (StringUtil.isNotEmpty(dataStr)) {
                    // 一分钟 可以发几次
                    Long sendXz = Long.parseLong(dataStr);
                    if (sendXz <= count) {
                        return new Result().error("一分钟内限制,可以发" + sendXz + "次;现已发送" + count + "次。");
                    }
                }
            }
        }
        return new Result().ok("可以发送");
    }

    @PostMapping("hotCarBrandList")
    @ApiOperation("热门车辆品牌列表")
    public Result<List<Map<String, Object>>> hotCarBrandList() {
        return new Result().ok(autobrandService.getHotCarBrandList());
    }

    @PostMapping("carGroupList")
    @ApiOperation("车辆车系列表")
    public Result<List<Map<String, Object>>> carGroupList(@RequestBody CarInfoDTO dto) {
        return new Result().ok(autogroupService.getCarGroupList(dto.getAutoBrandFk()));
    }

    @PostMapping("carKindsList")
    @ApiOperation("车辆类别列表")
    public Result<List<Map<String, Object>>> carKindsList() {
        return new Result().ok(autokindsService.getCarKindsList());
    }

    @PostMapping("carBrandList")
    @ApiOperation("车辆品牌列表")
    public Result<List<Map<String, Object>>> carBrandList() {
        return new Result().ok(autobrandService.getCarBrandList());
    }

    @PostMapping("carYearList")
    @ApiOperation("车辆年份列表")
    public Result<List<Map<String, Object>>> carYearList(@RequestBody CarInfoDTO dto) {
        if (StringUtil.isEmpty(dto.getAutoGroupFk())) {
            return new Result().error("车系ID不能为空");
        }
        return new Result().ok(automodelsService.getCarYearList(dto.getAutoGroupFk()));
    }

    @PostMapping("carDisplacementList")
    @ApiOperation("车辆排量列表")
    public Result<List<Map<String, Object>>> carDisplacementList(@RequestBody CarInfoDTO dto) {
        if (StringUtil.isEmpty(dto.getAutoGroupFk())) {
            return new Result().error("车系ID不能为空");
        }
        return new Result().ok(automodelsService.getCarDisplacementList(dto.getAutoGroupFk(), dto.getAutoYear()));
    }

    @PostMapping("carTypeList")
    @ApiOperation("车辆排量列表")
    public Result<List<Map<String, Object>>> carTypeList(@RequestBody CarTypeDto dto) {
        if (StringUtil.isEmpty(dto.getAutoGroupFk())) {
            return new Result().error("车系ID不能为空");
        }
        return new Result().ok(automodelsService.carTypeList(dto));
    }


    @PostMapping("carConfigList")
    @ApiOperation("车辆配置列表")
    public Result<List<Map<String, Object>>> carConfigList(@RequestBody CarInfoDTO dto) {
        if (StringUtil.isEmpty(dto.getAutoGroupFk())) {
            return new Result().error("车系ID不能为空");
        }
        return new Result().ok(automodelsService.getCarConfigList(dto.getAutoGroupFk(), dto.getAutoYear()));
    }

    @PostMapping("storeList")
    @ApiOperation("门店列表")
    public Result<List<UcmlOrganizeRepon>> storeList(@RequestBody StoreInfoDTO dto) {
        return new Result().ok(ucmlOrganizeService.getStoreList(dto.getLat(), dto.getLon()));
    }


    @PostMapping("identifyByVin")
    @ApiOperation("vin码识别")
    public Result<String> identifyByVin() {
        return new Result().ok("http://58.216.180.2:8405/API/Auth/GetVIN");
    }

    @PostMapping("identifyByXsz")
    @ApiOperation("行驶证识别")
    public Result<String> identifyByXsz() {
        return new Result().ok("http://58.216.180.2:8405/API/Auth/GetXXZSB");
    }


    @PostMapping("getModelByVin")
    @ApiOperation("通过vin码获取车型")
    public Result<String> getModelByVin(@RequestBody VinInfoDTO dto) {
        if (StringUtil.isEmpty(dto.getVin())) {
            return new Result().error("参数异常");
        }
        VinQuery query = new VinQuery();
        query.setVin(dto.getVin());
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getCarVinInfo(query);
        if (result != null) {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
            return new Result().ok(jsonObject.get("carList"));
        }
        return new Result();
    }

    @PostMapping("identifyByVinHost")
    @ApiOperation("vin码识别域名")
    public Result<String> identifyByVinHost() {
        return new Result();
    }

    @PostMapping("getBookableTimeList")
    @ApiOperation("获取门店的可预约时间段")
    public Result<String> getBookableTimeList(@RequestBody StoreInfoDTO storeInfoDTO) {
        if (StringUtil.isEmpty(storeInfoDTO.getOrgFK())) {
            return new Result().error("参数异常");
        }
        StoreQuery query = new StoreQuery();
        query.setOrgFK(storeInfoDTO.getOrgFK());
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getReservationTimePoint(query);
        if (result != null) {
            return new Result().ok(result);
        }
        return new Result();
    }


    @PostMapping("autoNoCheckFlag")
    @ApiOperation("是否校验车牌")
    public Result<String> autoNoCheckFlag() {
        return new Result().ok(sysparamService.getAutoNoCheckFlag());
    }


    @PostMapping("syncExistGroup")
    @ApiOperation("同步现有的群组")
    public Result<String> syncExistGroup() {
        StoreQuery query = new StoreQuery();
        //query.setOrgFK(storeInfoDTO.getOrgFK());
        //        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getReservationTimePoint(query);

        return new Result().ok(sysparamService.getAutoNoCheckFlag());
    }

    @Autowired
    private WxMaService wxMaService;

    @GetMapping("getQueryURLLink")
    @ApiOperation("查询加密URLLink")
    public Result<String> getQueryURLLink(String path) {
        try {
            QueryUrlLinkRequest request = QueryUrlLinkRequest.builder().urlLink(path).build();
            QueryUrlLinkResponse urlLinkResponse = wxMaService.getLinkService().queryUrlLink(request);
            return new Result().ok(urlLinkResponse);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping("getGenerateURLLink")
    @ApiOperation("获取加密URLLink")
    public Result<String> getGenerateURLLink(String path, String query, String envVersion) {
        try {
            GenerateUrlLinkRequest request = GenerateUrlLinkRequest.builder().path(path).query(query).envVersion(envVersion).build();
            String resStr = wxMaService.getLinkService().generateUrlLink(request);
            return new Result().ok(resStr.replaceAll("\"", ""));
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

    }

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;


    @PostMapping("addChatGroupMember")
    @ApiOperation("群创建成功后，加入成员")
    public Result<String> addChatGroupMember(@RequestBody AddChatGroupMemberDTO addChatGroupMemberDTO) {
        String result = tencentCloudImUtil.addGroupMember(addChatGroupMemberDTO.getGroupId(), addChatGroupMemberDTO.getMemberList());
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("OK".equals(jsonObject.getString("ActionStatus"))) {
            return new Result().ok("加入成功");
        }
        return new Result().error(jsonObject.getString("ErrorInfo"));
    }

}